package com.hq.ims.platform.busservice;

import com.hq.authority.utils.AppUtils;
import com.hq.ims.data.config.verification.VdAdd;
import com.hq.ims.data.config.verification.VdEdit;
import com.hq.ims.data.entity.*;
import com.hq.ims.data.entityenum.EnumBusinessTypeStatus;
import com.hq.ims.data.entityenum.EnumChangeWay;
import com.hq.ims.data.entityenum.EnumPublishStatus;
import com.hq.ims.data.entityenum.EnumReceiveStatus;
import com.hq.ims.data.event.BusInfoNotificationEvent;
import com.hq.ims.data.service.*;
import com.hq.ims.data.utils.ErrMsgConstant;
import com.hq.ims.data.utils.LocalConstant;
import com.hq.ims.data.utils.WebExpandUtils;
import com.hq.ims.data.vo.*;
import com.hq.utils.util.BooleanUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yinzhangxiao
 * @date 2024/10/25 17:06
 * @ClassName PlatformBigDataService
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class PlatformBigDataService {

    @Resource
    private BaseBusiIndustryCompanyService baseBusiIndustryCompanyService;
    @Resource
    private BaseBusiHistoryService baseBusiHistoryService;
    @Resource
    private BaseBusInfoNotificationService baseBusInfoNotificationService;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private BaseBusiChangeService baseBusiChangeService;
    @Resource
    private BaseBusiInfoService baseBusiInfoService;

    /**
     * @description: 大数据采集新增
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:28
     */
    @Transactional(rollbackFor = Exception.class)
    public void addBusiInfo(BusiInfoMapstruct.SaveVo vo) {
        //验证数据是否为空
        SpringBootValidateUtils.validate(vo, VdAdd.class);
        vo.setOrgId(WebExpandUtils.getHeadCompanyId());
        vo.setInfoType(EnumBusinessTypeStatus.BigData);
        //数据校验
        baseBusiInfoService.validate(null,vo, LocalConstant.INSERT);
        //查询省市code
        baseBusiInfoService.setAreaCode(vo);
        vo.setPublishStatus(EnumPublishStatus.Unreleased);
        vo.setPublisherId(AppUtils.getUserId());
        vo.setPublisher(AppUtils.getCurrentUser().getRealName());
        vo.setAcceptStatus(EnumReceiveStatus.UnReceive);
        vo.setContactPerson(AppUtils.getCurrentUser().getRealName());
        vo.setContactInfomation(AppUtils.getCurrentUser().getMobile());
        vo.setParentId("0");
        //拼接信息表产业标记字段
        baseBusiInfoService.setBusiIndustryAssign(vo);
        BusiInfo busiInfo = baseBusiInfoService.addData(vo);
        vo.setBusiInfoId(busiInfo.getBusiInfoId());
        //计算相似度
        BigDecimal repetitionRate = baseBusiInfoService.calcSimilarityRate(vo);
        busiInfo.setRepetitionRate(repetitionRate.setScale(0, RoundingMode.HALF_UP).doubleValue());
        busiInfo.setRootId(busiInfo.getBusiInfoId());
        busiInfo.setVersion(0);
        baseBusiInfoService.updateById(busiInfo);
        //保存产业标记指派以及补全并保存产业标记公司
        baseBusiInfoService.saveBusiIndustryAssignList(vo);

        //插入历史表
        BusiHistoryMapstruct.SaveVo build = new BusiHistoryMapstruct.SaveVo();
        BeanUtils.copyProperties(busiInfo, build);
        baseBusiHistoryService.addData(build);


    }

    /**
     * @description: 大数据采集修改
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:29
     */
    @Transactional(rollbackFor = Exception.class)
    public void editBusiInfo(BusiInfoMapstruct.SaveVo vo) {
        //验证数据是否为空
        SpringBootValidateUtils.validate(vo, VdEdit.class);
        vo.setInfoType(EnumBusinessTypeStatus.BigData);
        //验证数据是否存在
        BusiInfo entity = baseBusiInfoService.getById(vo.getBusiInfoId());
        ObjectUtils.isNullThrow(entity, ErrMsgConstant.PROJECT_INFO_NOT_EXITS);
        //数据校验
        baseBusiInfoService.validate(entity,vo, LocalConstant.EDIT);
        //查询省市code
        baseBusiInfoService.setAreaCode(vo);
        baseBusiInfoService.setBusiIndustryAssign(vo);
        vo.setUpdateDateTime(LocalDateTime.now());
        vo.setUpdateUserName(AppUtils.getCurrentUser().getRealName());
        BusiInfo busiInfo = baseBusiInfoService.editData(vo);
        List<Map<String, Object>> maps = new ArrayList<>();
        baseBusiInfoService.compareIndustry(vo,maps);
        if (CollectionUtils.isNotEmpty(maps)){
            List<BusiChange> changeList = new ArrayList<>(maps.size());
            maps.forEach(map->{
                BusiChange busiChange = new BusiChange();
                busiChange.setBusiInfoId(vo.getBusiInfoId());
                busiChange.setChangeContent(MapUtils.getString(map,"name"));
                busiChange.setChangeBefore(MapUtils.getString(map,"changeBefore"));
                busiChange.setChangeAfter(MapUtils.getString(map,"changeAfter"));
                busiChange.setChangeTime(LocalDateTime.now());
                busiChange.setChangeWay(EnumChangeWay.AdminChange);
                changeList.add(busiChange);
            });
            baseBusiChangeService.saveBatch(changeList);
        }
        //插入历史表
        baseBusiHistoryService.saveBusiChangeTimeRecord(busiInfo);
        //保存产业标记指派以及补全并保存产业标记公司
        baseBusiInfoService.saveBusiIndustryAssignList(vo);
    }

    /**
     * @description: 大数据采集发布
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:29
     */
    @Transactional(rollbackFor = Exception.class)
    public void publishData(String busiInfoId) {
        BusiInfo busiInfo = baseBusiInfoService.getById(busiInfoId);
        //验证数据是否存在
        ObjectUtils.isNullThrow(busiInfo, ErrMsgConstant.PROJECT_INFO_NOT_EXITS);
        //验证数据状态
        Boolean publishStatusFlag = EnumPublishStatus.Released.getCode() == busiInfo.getPublishStatus().getCode();
        BooleanUtils.isTrueThrow(publishStatusFlag, ErrMsgConstant.PROJECT_INFO_PUBLISH_STATUS_EXCEPTION);
        busiInfo.setPublishStatus(EnumPublishStatus.Released);
        busiInfo.setPublishTime(LocalDateTime.now());
        busiInfo.setRootId(busiInfo.getRootId());
        baseBusiInfoService.updateById(busiInfo);
        //推送经营信息到指定公司
        List<BusiIndustryCompany> list = baseBusiIndustryCompanyService.lambdaQuery().eq(BusiIndustryCompany::getBusiInfoId, busiInfoId).list();
        List<BusInfoNotification> notificationList = new ArrayList<>(list.size());
        list.forEach(item -> {
            BusInfoNotification busInfoNotification = new BusInfoNotification();
            busInfoNotification.setBusiInfoId(busiInfoId);
            busInfoNotification.setIndustryMarkId(item.getIndustryId());
            busInfoNotification.setIndustryMarkName(item.getIndustryName());
            busInfoNotification.setCompanyId(item.getCompanyId());
            busInfoNotification.setCompanyName(item.getCompanyName());
            busInfoNotification.setOrgId(busiInfo.getOrgId());
            busInfoNotification.setReceiveStatus(EnumReceiveStatus.UnReceive);
            busInfoNotification.setNotificationWay(item.getNotificationWay());
            notificationList.add(busInfoNotification);
        });
        baseBusInfoNotificationService.saveBatch(notificationList);
        for (BusInfoNotification busInfoNotification : notificationList) {
            //推到公司事件
            applicationContext.publishEvent(new BusInfoNotificationEvent(this, busInfoNotification, BusInfoNotificationEvent.PUSH_TO_COMPANY));
        }
    }

    /**
     * @description: 大数据采集作废
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:30
     */
    @Transactional(rollbackFor = Exception.class)
    public void obsoleteData(String busiInfoId) {
        BusiInfo busiInfo = baseBusiInfoService.getById(busiInfoId);
        //验证数据是否存在
        ObjectUtils.isNullThrow(busiInfo, ErrMsgConstant.PROJECT_INFO_NOT_EXITS);
        //状态
        Boolean remarkFlag = EnumPublishStatus.Unreleased.getCode() == busiInfo.getPublishStatus().getCode();
        BooleanUtils.isFalseThrow(remarkFlag, ErrMsgConstant.PROJECT_INFO_PUBLISH_STATUS_EXCEPTION);
        busiInfo.setPublishStatus(EnumPublishStatus.Obsolete);
        baseBusiInfoService.updateById(busiInfo);
    }

}
